package com.zl.service.impl;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.zl.Util.SSHCmdUtil;
import com.zl.service.LogService;
import org.codehaus.groovy.runtime.metaclass.ConcurrentReaderHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhoul
 * @since 2016-09-19-15:50
 */
public class LogServiceImpl implements LogService {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogServiceImpl.class);
    private static final Map<Object, InputStream> inputStreamMap;
    private static final Map<Object, Channel> channelMap;

    static {
        inputStreamMap = new HashMap<>();
        channelMap = new HashMap<>();
    }

    @Override
    public String getMessage() {
        return null;
    }

    @Override
    public void showLog(String user, String pwd, String ip, String path, WebSocketSession sessionSocket) throws JSchException, IOException {
        LOGGER.info("showLog " + sessionSocket + ", thread = " + Thread.currentThread());
        Session sessionSSH = SSHCmdUtil.getSession(user, pwd, ip, 22);
        Channel channel;
        channel = sessionSSH.openChannel("exec");
        ((ChannelExec) channel).setCommand("tail -f " + path);
        channel.setInputStream(null);

        ((ChannelExec) channel).setErrStream(System.err);
        InputStream in = channel.getInputStream();
        channel.connect();
        inputStreamMap.put(sessionSocket.getId(), in);
        channelMap.put(sessionSocket.getId(), channel);

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null) {
            // 将实时日志通过WebSocket发送给客户端，给每一行添加一个HTML换行
            System.out.println(line);
            sessionSocket.sendMessage(new TextMessage(line));
        }
    }

    @Override
    public void closeInputStreamAndChannel(WebSocketSession session) {
        if (channelMap.containsKey(session.getId())) {
            Channel channel;
            channel = channelMap.get(session.getId());
            if (channel != null) {
                channel.disconnect();
            }
            channelMap.remove(session.getId());
        }
        if (inputStreamMap.containsKey(session.getId())) {
            InputStream inputStream;
            inputStream = inputStreamMap.get(session.getId());
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            inputStreamMap.remove(session.getId());
        }

    }


}
